<template>
  <div class="app">
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>遗产信息平台</a-breadcrumb-item>
      <a-breadcrumb-item>遗产要素</a-breadcrumb-item>
    </a-breadcrumb>
    <a-row>
      <a-col :span="6">
        名称：
        <a-input placeholder="请输入" v-model="query.name" />
      </a-col>
      <a-col :span="8">
        发布时间：
        <a-range-picker
          style="width: 330px"
          v-model="dateRange"
          :placeholder="['开始日期', '结束日期']"
          valueFormat="YYYY-MM-DD HH:mm:ss"
          :show-time="{
            hideDisabledOptions: true,
            defaultValue: [
              moment('00:00:00', 'HH:mm:ss'),
              moment('23:59:59', 'HH:mm:ss'),
            ],
          }"
          format="YYYY-MM-DD HH:mm:ss"
          @change="createTime1"
        />
      </a-col>
      <a-col :span="6">
        文号：
        <a-input placeholder="请输入" v-model="query.number" />
      </a-col>
      <a-col :span="6">
        地址：
        <a-input placeholder="请输入" v-model="query.address" />
      </a-col>
      <!-- <a-col :span="6">
        遗产类型：
        <a-select v-model="query.type">
          <a-select-option
            v-for="item in ycList"
            :value="item.dictValue"
            :key="item.id"
          >
            {{ item.dictValue }}
          </a-select-option>
        </a-select>
      </a-col> -->
      <a-col :span="4">
        <a-button type="primary" @click="getQuery"> 查询 </a-button>&emsp;&nbsp;
        <a-button @click="cleanQuery">重置</a-button>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="24">
        <!-- @change="getQuery1" -->
        <a-radio-group  @change="getQuery1">
          &emsp;&emsp;遗产本体：
          <a-radio-button
            v-for="item in ycList"
            :value="item.dictValue"
            :key="item.id"
          >
            {{ item.dictValue }}
          </a-radio-button> </a-radio-group
        ><br /><br />
        <a-radio-group @change="getQuery2">
          &emsp;&emsp;保护等级：
          <a-radio-button
            v-for="item in djList"
            :value="item.dictValue"
            :key="item.id"
          >
            {{ item.dictValue }}
          </a-radio-button>
        </a-radio-group>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="4">遗产要素列表</a-col>
      <a-col :span="18"></a-col>
      <a-col :span="2">
        <a-button
          type="primary"
          @click="addData"
          v-hasPermi="['yichan:ycys:add']"
        >
          新建
        </a-button>
      </a-col>
      <a-col :span="24">
        <a-table
          :columns="columns"
          :data-source="data"
          :rowKey="
            (record, index) => {
              return index;
            }
          "
          :pagination="false"
        >
          <span slot="img" slot-scope="text, record">
            <img
              v-if="text"
              :src="text"
              @click="openPic(text)"
              style="width: 100px; height: 100px"
            />
            <div v-else>暂无图片</div>
          </span>
          <span slot="action" slot-scope="text, record">
            <a @click="changeData1(record)" v-hasPermi="['yichan:ycys:view']"
              >查看</a
            >
            <a-divider type="vertical" />
            <a @click="changeData(record)" v-hasPermi="['yichan:ycys:edit']"
              >编辑</a
            >
            <a-divider type="vertical" />
            <a-popconfirm
              placement="left"
              title="您正在进行删除操作，删除后数据不可恢复，确定删除吗？"
              ok-text="确认"
              class="red"
              cancel-text="取消"
              @confirm="deleteData(record)"
              v-hasPermi="['yichan:ycys:del']"
            >
              <a>删除</a> </a-popconfirm
            >&nbsp;
          </span>
        </a-table>
        <a-locale-provider :locale="$zhCN">
          <a-pagination
            style="float: right; margin-top: 10px"
            v-model="query.offset"
            show-size-changer
            :total="total"
            :page-size-options="pageSizeOptions"
            :page-size="query.current"
            @change="pageChange"
            @showSizeChange="pageSizeChange"
            :show-total="(total) => `共 ${total} 条`"
          />
        </a-locale-provider>
      </a-col>
      <a-modal
        v-model="vis"
        width="50%"
        title="档案"
        ok-text="确认"
        cancel-text="取消"
        @ok="handleOk"
        @cancel="handleClose"
      >
        <a-row>
          <a-col :span="3"> 遗产名称： </a-col>
          <a-col :span="9">
            <a-input
              placeholder="请输入"
              v-model="newData.name"
              style="width: 80%"
            />
          </a-col>
          <a-col :span="3"> 遗产文号： </a-col>
          <a-col :span="9">
            <a-input
              placeholder="请输入"
              v-model="newData.number"
              style="width: 80%"
            />
          </a-col>
          <a-col :span="3"> 遗产地址： </a-col>
          <a-col :span="9">
            <a-input
              placeholder="请输入"
              v-model="newData.address"
              style="width: 80%"
            />
          </a-col>
          <a-col :span="3"> &emsp;&emsp;年代： </a-col>
          <a-col :span="9">
            <a-date-picker
              :locale="$locale"
              mode="year"
              format="YYYY"
              v-model="newData.age"
              placeholder="请输入"
              @panelChange="createYear"
              style="width: 80%"
            />
          </a-col>
          <a-col :span="3"> 发布时间： </a-col>
          <a-col :span="9">
            <a-date-picker
              :locale="$locale"
              placeholder="请输入"
              v-model="newData.publishtime"
              @change="createTime"
              style="width: 80%"
            />
          </a-col>
          <a-col :span="3"> 遗产类型： </a-col>
          <a-col :span="9">
            <a-select v-model="newData.type" style="width: 80%">
              <a-select-option
                v-for="item in ycList"
                :value="item.dictValue"
                :key="item.id"
              >
                {{ item.dictValue }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :span="3"> 遗产级别： </a-col>
          <a-col :span="9">
            <a-select v-model="newData.level" style="width: 80%">
              <a-select-option :value="1"> 文物保护单位 </a-select-option>
              <a-select-option :value="2"> 重点保护民居 </a-select-option>
              <a-select-option :value="3"> 保护民居 </a-select-option>
              <a-select-option :value="4"> 历史建筑 </a-select-option>
            </a-select>
          </a-col>
          <a-col :span="3"> 遗产图片： </a-col>
          <a-col :span="9">
            <a-upload
              name="file"
              :before-upload="handleFileUpload"
              :file-list="fileList"
              :customRequest="submitFile"
              :remove="handleFileRemove"
            >
              <a-button>
                <a-icon type="upload" />
                上传文件
              </a-button>
            </a-upload>
          </a-col>
          <!-- <a-col :span="3"> &emsp;&emsp;描述： </a-col> -->
          <!-- <a-col :span="21">
            <a-textarea
              v-model="newData.desc"
              placeholder="请输入"
              :rows="4"
              style="width: 90%"
            />
          </a-col> -->
        </a-row>
      </a-modal>
      <a-modal
        v-model="vis2"
        width="50%"
        title="遗产要素"
        ok-text="确认"
        cancel-text="取消"
        @ok="changeOk"
        @cancel="handleClose"
      >
        <a-row>
          <a-col :span="3"> 遗产名称： </a-col>
          <a-col :span="9">
            <a-input
              placeholder="请输入"
              v-model="newData.name"
              style="width: 80%"
            />
          </a-col>
          <a-col :span="3"> 遗产文号： </a-col>
          <a-col :span="9">
            <a-input
              placeholder="请输入"
              v-model="newData.number"
              style="width: 80%"
            />
          </a-col>
          <a-col :span="3"> 遗产地址： </a-col>
          <a-col :span="9">
            <a-input
              placeholder="请输入"
              v-model="newData.address"
              style="width: 80%"
            />
          </a-col>
          <a-col :span="3"> &emsp;&emsp;年代： </a-col>
          <a-col :span="9">
            <a-date-picker
              mode="year"
              format="YYYY"
              v-model="newData.age"
              placeholder="请输入"
              @panelChange="createYear"
              style="width: 80%"
            />
          </a-col>
          <a-col :span="3"> 发布时间： </a-col>
          <a-col :span="9">
            <a-date-picker
              :locale="$locale"
              placeholder="请输入"
              v-model="newData.publishtime"
              @change="createTime"
              style="width: 80%"
            />
          </a-col>
          <a-col :span="3"> 遗产类型： </a-col>
          <a-col :span="9">
            <a-select v-model="newData.type" style="width: 80%">
              <a-select-option
                v-for="item in ycList"
                :value="item.dictValue"
                :key="item.id"
              >
                {{ item.dictValue }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :span="3"> 遗产级别： </a-col>
          <a-col :span="9">
            <a-select v-model="newData.level" style="width: 80%">
              <a-select-option :value="1"> 文物保护单位 </a-select-option>
              <a-select-option :value="2"> 重点保护民居 </a-select-option>
              <a-select-option :value="3"> 保护民居 </a-select-option>
              <a-select-option :value="4"> 历史建筑 </a-select-option>
            </a-select>
          </a-col>
          <a-col :span="3"> 遗产图片： </a-col>
          <a-col :span="9">
            <a-upload
              accept=".jpg,.png,.jpeg"
              name="file"
              :before-upload="handleImgUpload"
              :file-list="imgList"
              :customRequest="submitFile"
              :remove="handleRemove"
            >
              <a-button>
                <a-icon type="upload" />
                上传图片
              </a-button>
            </a-upload>
          </a-col>
          <!-- <a-col :span="3"> &emsp;&emsp;描述： </a-col>
          <a-col :span="21">
            <a-textarea
              v-model="newData.desc"
              placeholder="请输入"
              :rows="4"
              style="width: 90%"
            />
          </a-col> -->
        </a-row>
      </a-modal>
      <a-drawer
        title="档案详情"
        width="33%"
        placement="right"
        :closable="false"
        :visible="vis1"
        @close="vis1 = false"
      >
        <a-row>
          <a-col :span="3" style="color: #00000080">名称：</a-col>
          <a-col :span="8">{{ oldData.name }}</a-col>
          <a-col :span="3" style="color: #00000080">图片：</a-col>
          <a-col :span="8">{{ oldData.img }}</a-col>
          <a-col :span="3" style="color: #00000080">级别：</a-col>
          <a-col :span="8">{{ oldData.level }}</a-col>
          <a-col :span="4" style="color: #00000080">发布时间：</a-col>
          <a-col :span="8">{{ oldData.publishtime }}</a-col>
          <a-col :span="3" style="color: #00000080">文号：</a-col>
          <a-col :span="8">{{ oldData.number }}</a-col>
          <a-col :span="3" style="color: #00000080">年代：</a-col>
          <a-col :span="8">{{ oldData.age }}</a-col>
          <a-col :span="3" style="color: #00000080">地址：</a-col>
          <a-col :span="8">{{ oldData.address }}</a-col>
          <a-col :span="4" style="color: #00000080">遗产类型：</a-col>
          <a-col :span="8">
            <div v-if="oldData.type == 1">文化遗产类型A</div>
            <div v-else>文化遗产类型B</div>
          </a-col>
        </a-row>
      </a-drawer>
    </a-row>
  </div>
</template>
<script>
import moment from "moment";
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    title: "名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "图片",
    dataIndex: "img",
    key: "img",
    scopedSlots: { customRender: "img" },
  },
  {
    title: "级别",
    dataIndex: "level",
    key: "level",
  },
  {
    title: "发布时间",
    dataIndex: "publishtime",
    key: "publishtime",
  },
  {
    title: "文号",
    dataIndex: "number",
    key: "number",
  },
  {
    title: "年代",
    dataIndex: "age",
    key: "age",
  },
  {
    title: "地址",
    dataIndex: "address",
    key: "address",
  },
  {
    title: "遗产类型",
    dataIndex: "type",
    key: "type",
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" },
  },
];
export default {
  mounted() {
    this.getList();
  },
  data() {
    return {
      dateRange: [],
      button: [],
      data: [],
      columns,
      vis: false,
      vis1: false,
      vis2: false,
      vis3: false,
      pageSizeOptions: ["10", "20", "50"],
      total: 0,
      query: {
        current: 20,
        offset: 1,
        name: "",
        number: "",
        address: "",
        type: "",
        startTime: "",
        endTime: "",
      },
      newData: {
        name: "",
        number: "",
        address: "",
        age: "",
        publishtime: "",
        type: "",
        level: "",
        img: "",
        desc: "",
      },
      oldData: {},
      file: null,
      fileList: [],
      oldtime: "",
      ycList: [],
      djList: [],
      imgList: [],
    };
  },

  methods: {
    moment,
    getQuery() {
      this.query.offset = 1;
      this.getList();
    },
    getQuery1(e) {
      this.query.type = e.target.value;
      var q = "/government-platform-center/heritageInfo";
      this.$axios.get(q, { params: this.query }).then((res) => {
        if (res.data.msg == "success") {
          for (let i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].img.slice(0, 18) == "http://172.17.5.29") {
              res.data.data[i].img = res.data.data[i].img.replace(
                "http://172.17.5.29",
                "http://61.166.9.9:8080"
              );
            }
          }
          this.data = res.data.data;
          this.total = res.data.total;
        }
      });
    },
    getQuery2(e) {
      this.query.level = e.target.value;
      var q = "/government-platform-center/heritageInfo";
      this.$axios.get(q, { params: this.query }).then((res) => {
        if (res.data.msg == "success") {
          for (let i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].img.slice(0, 18) == "http://172.17.5.29") {
              res.data.data[i].img = res.data.data[i].img.replace(
                "http://172.17.5.29",
                "http://61.166.9.9:8080"
              );
            }
          }
          this.data = res.data.data;
          this.total = res.data.total;
        }
      });
    },
    cleanQuery() {
      this.query = {
        current: 20,
        offset: 1,
        name: "",
        number: "",
        address: "",
        type: "",
        startTime: "",
        endTime: "",
      };
      this.dateRange = [];
      this.getList();
    },
    getList() {
      var q = "/government-platform-center/heritageInfo";
      let params = {
        ...this.query,
        number: encodeURIComponent(this.query.number),
      };
      console.log(params, "params");

      this.$axios.get(q, { params: params }).then((res) => {
        if (res.data.msg == "success") {
          for (let i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].img.slice(0, 18) == "http://172.17.5.29") {
              res.data.data[i].img = res.data.data[i].img.replace(
                "http://172.17.5.29",
                "http://61.166.9.9:8080"
              );
            }
          }
          this.data = res.data.data;
          this.total = res.data.total;
        }
      });

      this.$axios
        .get(
          "/government-platform-center/dictData/queryByCode?dictType=yichan_code"
        )
        .then((res) => {
          if (res.data.msg == "success") {
            this.ycList = res.data.data;
            // console.log(this.ycList);
          }
        });
      this.$axios
        .get(
          "/government-platform-center/dictData/queryByCode?dictType=yichan_proted_level"
        )
        .then((res) => {
          if (res.data.msg == "success") {
            this.djList = res.data.data;
            // console.log(this.djList);
          }
        });
    },
    pageChange(current) {
      this.query.offset = current;
      this.getList();
    },
    pageSizeChange(current, pageSize) {
      this.query.current = pageSize;
      this.query.offset = current;
      this.getList();
    },
    addData() {
      this.vis = true;
    },
    handleFileUpload(event, _) {
      this.file = event;
      this.fileList.push(event);
    },
    handleImgUpload(event, _) {
      this.file = event;
      this.imgList.push(event);
    },
    submitFile() {
      const query = {
        multipartFile: this.file,
      };
      this.$axios
        .post("/government-platform-center/common/uploadFile", query, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((response) => {
          this.$message.success("上传成功");
          this.newData.img = response.data.data;
        });
    },
    handleOk() {
      var parmas = this.newData;
      const year = parmas.age._d.getFullYear();
      const month = (parmas.age._d.getMonth() + 1).toString().padStart(2, "0");
      const day = parmas.age._d.getDate().toString().padStart(2, "0");
      parmas.age = year + "-" + month + "-" + day;
      this.$axios
        .post("/government-platform-center/heritageInfo", parmas, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          if (res.data.msg == "success") {
            this.getList();
            this.vis = false;
            this.newData = {
              name: "",
              number: "",
              address: "",
              age: "",
              publishtime: "",
              type: "",
              level: "",
              img: "",
              desc: "",
            };
          }
        });
    },
    changeOk() {
      var parmas = this.newData;
      if (parmas.age != this.oldtime) {
        const year = parmas.age._d.getFullYear();
        const month = (parmas.age._d.getMonth() + 1)
          .toString()
          .padStart(2, "0");
        const day = parmas.age._d.getDate().toString().padStart(2, "0");
        parmas.age = year + "-" + month + "-" + day;
      }
      this.$axios
        .post("/government-platform-center/heritageInfo/edit", parmas, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          if (res.data.msg == "success") {
            this.getList();
            this.vis2 = false;
            this.newData = {
              name: "",
              number: "",
              address: "",
              age: "",
              publishtime: "",
              type: "",
              level: "",
              img: "",
              desc: "",
            };
            this.vis3 = false;
          }
        });
    },
    createTime(date, dateString) {
      this.newData.publishtime = dateString;
    },
    createYear(date) {
      this.newData.age = date;
    },
    createTime1(val) {
      this.query.startTime = val[0];
      this.query.endTime = val[1];
    },
    changeData(record) {
      this.newData = record;
      this.oldtime = record.age;
      this.vis2 = true;
    },
    changeData1(record) {
      this.$router.push({
        path: "/yichan/Yichanxq",
        query: {
          id: record.id,
        },
      });
    },
    handleClose() {
      this.newData = {
        name: "",
        number: "",
        address: "",
        age: "",
        publishtime: "",
        type: "",
        level: "",
        img: "",
        desc: "",
      };
    },
    deleteData(record) {
      var parmas = {
        id: record.id,
      };
      // 首先检查记录是否包含图片
      const hasImage = record.img && record.img.trim() !== "";

      this.$axios
        .post("government-platform-center/heritageInfo/deleteById", parmas, {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          if (res.data.msg == "success") {
            // 如果删除数据库记录成功且有图片，尝试删除图片文件
            if (hasImage) {
              // 从图片URL中提取文件名
              const imgUrl = record.img;
              const fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);

              // 可选：如果后端有删除文件的API，可以调用它
              // this.$axios.post('government-platform-center/common/deleteFile', { fileName: fileName })
              //   .then(resp => {
              //     console.log('图片文件删除成功');
              //   })
              //   .catch(err => {
              //     console.error('图片文件删除失败', err);
              //   });
            }

            this.$message.success("删除成功");
            this.getList();
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    lookData(record) {
      this.vis1 = true;
      this.oldData = record;
    },
    openPic(text) {
      console.log(text);
      window.open(text);
    },
    handleRemove(file) {
      // 从列表中删除图片
      const index = this.imgList.indexOf(file);
      const newFileList = this.imgList.slice();
      newFileList.splice(index, 1);
      this.imgList = newFileList;

      // 如果有图片URL，则清除图片
      if (this.newData.img && this.newData.img === file.url) {
        this.newData.img = "";
      }

      return true;
    },
    handleFileRemove(file) {
      // 从列表中删除文件
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;

      // 如果有文件，则清除文件
      if (this.file && this.file === file) {
        this.file = null;
      }

      return true;
    },
  },
};
</script>
<style scoped>
.ant-row {
  border-radius: 5px;
  margin-bottom: 15px;
  background: #fff;
  padding: 20px;
  color: #000;
}

/deep/.ant-table-thead > tr > th {
  color: #000;
  font-weight: bold;
}

/deep/.ant-table-tbody > tr > td {
  color: #000;
}

.ant-col {
  margin: 10px 0;
}

.ant-select {
  width: 60%;
}

.ant-input {
  width: 60%;
}

.file-upload-btn {
  background-color: #007bff;
  /* 背景颜色 */
  color: white;
  /* 文本颜色 */
  border: none;
  border-radius: 5px;
  padding: 10px;
  cursor: pointer;
  font-size: 16px;
}

.timeline {
  width: 400px;
  height: 100px;
  border: #007bff 1px solid;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
